//
//  BVPlayGroundViewController.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/10/12.
//

#import "BVPlayGroundViewController.h"
#import <MapKit/MapKit.h>
#import "BVService.h"
#import "SVProgressHUD.h"
#import "BVMetaModel.h"
#import "BVAnnotationView.h"
#import "BVAnnotationModel.h"
#import "BVLocationUtil.h"
#import "BVBasketBallPlaygroundTableViewCell.h"
#import "BVPlaygroundSearchView.h"
#import "BVPlaygroundDetailView.h"

@interface BVPlayGroundViewController ()<MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contanerViewHeight;

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *textFieldContainerView;
@property (weak, nonatomic) IBOutlet UITextField *inputView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerViewTopMargin;
@property (nonatomic, strong) NSMutableArray<BVMetaArena *> *dataSource;
@property (weak, nonatomic) IBOutlet UIView *tableContainerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet BVPlaygroundSearchView *searchView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *searchViewHeight;
@property (weak, nonatomic) IBOutlet UITableView *searchTableView;

@property (nonatomic, strong) BVPlaygroundDetailView *detailView;

@end

@implementation BVPlayGroundViewController

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadInitData];
    
}

- (void)layoutTableView {
    [self.tableView layoutIfNeeded];
    
    CGFloat height = self.tableView.contentSize.height > self.tableView.bounds.size.height ? self.tableView.contentSize.height : self.tableView.bounds.size.height;
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.tableView.bounds.size.width, height) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];

    CAShapeLayer * layer = [[CAShapeLayer alloc]init];

    layer.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, height);

    layer.path = path.CGPath;
    self.tableView.layer.mask = layer;
    
    if (_detailView) {
        CGFloat height = _detailView.height;
        UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, _detailView.bounds.size.width, height) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(8, 8)];

        CAShapeLayer * layer = [[CAShapeLayer alloc]init];

        layer.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, height);

        layer.path = path.CGPath;
        _detailView.layer.mask = layer;
    }
}

- (void)loadInitData {
    __weak typeof(self)weakSelf = self;
    [[BVLocationUtil sharedInstance] startLocationWithBlock:^(CLLocation * _Nonnull location) {
        if (location) {
            [weakSelf loadNetDataWithLocation:location];
        }else {
            [SVProgressHUD showErrorWithStatus:@"请允许定位"];
        }
    }];
}

- (void)errorView {
    __weak typeof(self)weakSelf = self;
    [BVErrorView showWithType:BVErrorViewTypePlayground inView:self.view retryBlock:^{
        [weakSelf loadInitData];
    }];
}

- (void)loadNetDataWithLocation:(CLLocation *)location {
    [[BVService shareInstance] get:@"arena" param:@{@"latitude": @(location.coordinate.latitude), @"longitude": @(location.coordinate.longitude)} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            [self handleDataWithArray:response[@"data"][@"results"]];
            if (self.dataSource.count == 0) {
                [self errorView];
            }
        }else {
            [self errorView];
            [SVProgressHUD showErrorWithStatus:@"服务异常"];
        }
    }];
}

- (void)handleDataWithArray:(NSArray<NSDictionary *> *)dataList {
    [dataList enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BVMetaArena *model = [[BVMetaArena alloc] initWithDictionary:obj error:nil];
        [self.dataSource addObject:model];
        BVAnnotationModel *annotation = [self buildAnnotationWithModel:model];
        [self.mapView addAnnotation:annotation];
    }];
    self.mapView.region = [[BVLocationUtil sharedInstance] regionForLocations:self.dataSource.copy];
    [self.tableView reloadData];
    [self layoutTableView];
}

- (BVAnnotationModel *)buildAnnotationWithModel:(BVMetaArena *)model {
    BVAnnotationModel *annotation = [[BVAnnotationModel alloc] initWithArean:model];
    return annotation;
}

- (void)onSelectArena:(BVMetaArena *)arena {
    self.inputView.text = @"";
    [self textFieldDidChangeText:self.inputView];
    [self.view endEditing:YES];
    
    [self.tableContainerView addSubview:self.detailView];
    [self.detailView configWithModel:arena];
    self.detailView.height = 303;
    self.contanerViewHeight.constant = 303;
    [self layoutTableView];
}

- (void)setupViews {
    self.searchView.hidden = YES;
    self.textFieldContainerView.layer.cornerRadius = 20;
    self.containerViewTopMargin.constant = kNavigationBarHeight - 44;
    self.tableContainerView.layer.shadowColor = [UIColor colorWithWhite:0 alpha:0.2].CGColor;
    self.tableContainerView.layer.shadowOffset = CGSizeMake(10, -10);
    self.tableContainerView.layer.shadowRadius = 10;
    self.tableContainerView.layer.shadowOpacity = 8;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BVBasketBallPlaygroundTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVBasketBallPlaygroundTableViewCell"];
    self.searchTableView.layer.cornerRadius = 10;
    self.searchTableView.clipsToBounds = YES;
    self.searchTableView.layer.masksToBounds = YES;
    self.searchTableView.delegate = self.searchView;
    self.searchTableView.dataSource = self.searchView;
    [self.searchTableView registerNib:[UINib nibWithNibName:@"BVPlaygroundSearchTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVPlaygroundSearchTableViewCell"];
    
    [self.inputView addTarget:self action:@selector(textFieldDidChangeText:) forControlEvents:UIControlEventEditingChanged];
    __weak typeof(self)weakSelf = self;
    self.searchView.selectBlock = ^(BVMetaArena * _Nonnull model) {
        [weakSelf onSelectArena:model];
    };
}

#pragma mark - textfield delegate
- (void)textFieldDidChangeText:(UITextField *)textField {
    if (textField.text.length > 0) {
        self.searchView.hidden = NO;
        [self.searchView configDataSource:[self dataSourceWithText:textField.text]];
        [self.searchTableView reloadData];
    }else {
        self.searchView.hidden = YES;
    }
}


- (NSArray *)dataSourceWithText:(NSString *)text {
    return [self.dataSource filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(BVMetaArena *  _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
        if ([evaluatedObject.name containsString:text]) {
            return YES;
        }else {
            return NO;
        }
    }]];
}

#pragma mark - tableview delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [BVBasketBallPlaygroundTableViewCell cellHeight];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BVBasketBallPlaygroundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVBasketBallPlaygroundTableViewCell" forIndexPath:indexPath];
    [cell configWithModel:self.dataSource[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self onSelectArena:self.dataSource[indexPath.row]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}


#pragma mark - mapview delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    static NSString *ANNOTATION_INDENTIFIER = @"ANNOTATION_INDENTIFIER";
    BVAnnotationView *_Nullable annotationView = (BVAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:ANNOTATION_INDENTIFIER];
    if (annotationView == nil) {
        annotationView = [[BVAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ANNOTATION_INDENTIFIER];
    }
    return annotationView;
}



#pragma mark -lazy load
- (NSMutableArray<BVMetaArena *> *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (BVPlaygroundDetailView *)detailView {
    if (!_detailView) {
        _detailView = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE] loadNibNamed:@"BVPlaygroundDetailView" owner:nil options:nil].firstObject;
        _detailView.frame = CGRectMake(self.tableView.frame.origin.x, 0, self.tableView.bounds.size.width, 303);
        __weak typeof(self)weakSelf = self;
        _detailView.backBlock = ^{
            weakSelf.contanerViewHeight.constant = 267;
        };
    }
    return _detailView;
}
@end
